package com.lw.leetcode.arr.b;

/**
 * Created with IntelliJ IDEA.
 * LCP 03. 机器人大冒险
 *
 * @author liw
 * @version 1.0
 * @date 2022/4/13 16:00
 */
public class Robot {

    private int m;
    private int n;
    private int length;
    private int[] arr;

    public boolean robot(String command, int[][] obstacles, int x, int y) {
        length = command.length();
        arr = new int[length];
        int a = (1 << 10);
        int item = 0;
        for (int i = 0; i < length; i++) {
            char c = command.charAt(i);
            if (c == 'R') {
                arr[i] = item + a;
            } else {
                arr[i] = item + 1;
            }
            item = arr[i];
        }
        m = arr[length - 1] >> 10;
        n = arr[length - 1] & 1023;
        if (!find(x, y)) {
            return false;
        }
        for (int[] obstacle : obstacles) {
            if (obstacle[0] <= x && obstacle[1] <= y && find(obstacle[0], obstacle[1])) {
                return false;
            }
        }
        return true;
    }

    private boolean find(int x, int y) {
        int a = 0;
        int b = 0;
        int s = (x + y) % length;
        if (s != 0) {
            int k = arr[s - 1];
            a += (k >> 10);
            b += (k & 1023);
        }
        int t = (x + y) / length;
        return m * t + a == x && n * t + b == y;
    }

}
